from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.contrib import auth
import random
from blogUtils.valid_code import valid_code
from django import forms
from django.forms import widgets
from blog.models import UserInfo, Article, Comment
from blog import models
from django.db.models import Count
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
import json

# Create your views here.
def login(request):
  if request.method == 'POST':
    response = {"user": None, "msg": None}
    user = request.POST.get('username')
    password = request.POST.get('password')
    validcode = request.POST.get('validcode')
    if validcode.upper() == request.session.get('valid_code_str').upper():
      user = auth.authenticate(username=user, password=password)
      if user:
        auth.login(request ,user)
        response['user'] = user.username
      else:
        response['msg'] = 'username or password error!'
    else:
      response['msg'] = 'valid code error'

    return JsonResponse(response)
  if request.method == 'GET':
    return render(request, 'login.html')

def get_valid_code(request):
  [data, chars] = valid_code()
  request.session['valid_code_str'] = chars
  
  return HttpResponse(data)


def index(request):
  article_list = Article.objects.all()
  return render(request, 'index.html', {'article_list': article_list, 'username': 'yjk'})

class UserForm(forms.Form):
  user = forms.CharField(max_length=32, error_messages={'required': '该字段不能为空'}, label='用户名', widget=widgets.TextInput(attrs={"class": "form-control"}))
  pwd = forms.CharField(max_length=32, label='密码', widget=widgets.PasswordInput(attrs={"class": "form-control"}))
  re_pwd = forms.CharField(max_length=32, label='确认密码', widget=widgets.PasswordInput(attrs={"class": "form-control"}))
  email = forms.EmailField(max_length=32, label='邮箱', widget=widgets.EmailInput(attrs={"class": "form-control"}))

  def clean_user(self):
    user = self.cleaned_data.get('user')
    # print(user)
    user = UserInfo.objects.filter(username=user).first()
    if not user:
      return self.cleaned_data.get('user')
    else:
      raise ValidationError('用户已存在')

def register(request):
  if request.method == 'POST':
    response = {"user": None, "msg": None}
    form = UserForm(request.POST)
    if form.is_valid():
      response['user'] = form.cleaned_data.get('user')
      print(form.cleaned_data)
      user = form.cleaned_data.get('user')
      email = form.cleaned_data.get('email')
      pwd = form.cleaned_data.get('pwd')
      print(user, email, pwd)
      UserInfo.objects.create(username=user, email=email,password=pwd)
      user_obj.save()
    else:
      response['msg'] = form.errors

    return JsonResponse(response)

  form = UserForm()


  return render(request, 'register.html', {'form': form})

def logout(request):
  auth.logout(request)
  redirect('/login')
  
def home_site(request, username,**kwgs):

  user = UserInfo.objects.filter(username=username).first()
  if not user:
    return render(request, '404.html')
  blog = user.blog
 
  article_list = Article.objects.filter(user=user)
  if kwgs:
    condition = kwgs.get('condition')
    parma = kwgs.get('params')
    if condition == 'category':
      article_list = article_list.filter(category__title=parma)
    elif condition == 'tag':
      article_list = article_list.filter(tags__title=parma)
    else :
      [year, month] = parma.split('-')
      article_list = article_list.filter(create_time__year=year, create_time__month=month)


  # 查询每个分类名称以及对应的文章数
  ret = models.Category.objects.values('pk').annotate(c=Count('article__title')).values('title', "c")
  # 查询当前站点名称以及对应的文章数
  cate_list = models.Category.objects.filter(blog=blog).values('pk').annotate(c=Count('article__title')).values('title', "c")
  # 查询当前站点每一个标签对应的文章数
  tag_list = models.Tag.objects.filter(blog=blog).values('pk').annotate(c=Count('article')).values_list('title', "c")
  # 查询当前站点每一个年月的名称和对应的文章数
  data_list = models.Article.objects.filter(user=user).extra(select={'y_m_d_date': "date_format(create_time,'%%Y-%%m')"}).values("y_m_d_date").annotate(c=Count('nid')).values('y_m_d_date', 'c')


  return render(request, 'index.html', {'article_list': article_list, 'ret': ret, 'cate_list': cate_list, 'tag_list': tag_list, 'data_list': data_list, 'username': username})
def article_detail(request, username, article_id):
  user = UserInfo.objects.filter(username=username).first()
  blog = user.blog
  article = Article.objects.filter(nid=article_id).first()
  comment_list = Comment.objects.filter(article_id=article_id)

  return render(request, 'article_detail.html', {'username': username, 'article': article, 'blog': blog, 'comment_list': comment_list})


from django.db.models import F
from django.http import JsonResponse
def digg(request):
  article_id = request.POST.get('article')
  is_up = json.loads(request.POST.get('is_up'))
  user_id = request.user.pk
  models.ArticleUpDown.objects.create(user_id=user_id, article_id=article_id, is_up=is_up)
  obj = models.ArticleUpDown.objects.filter(user_id=user_id, article_id=article_id).first()
  response = {"state": True}
  if not obj:
    query_set = models.Article.objects.filter(pk=article_id)
    if is_up:
      query_set.update(up_count=F('up_count')+1)
    else:
      query_set.update(down_count=F('up_count')+1)
  else:
    response['state'] = False
    response['handled'] = obj.is_up
  return JsonResponse(response)

def comment(request):
  response = {"state": True}
  articel_id = request.POST.get('article')
  content = request.POST.get('content')
  pid = request.POST.get('pid')
  user = request.user.pk
  Comment.objects.create(article_id=articel_id, content=content, parent_comment_id=pid, user_id=user)
  models.Article.objects.filter(pk=articel_id).update(comment_count=F('comment_count')+1)
  return JsonResponse(response)

def get_comment_tree(request):
  article = request.POST.get('article')
  ret = list(models.Comment.objects.filter(article_id=article).order_by('pk').values('pk', 'content', 'parent_comment_id'))
  return JsonResponse(ret, safe=False)